package com.jinbaoty.recyclebins.server.update;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.xuexiang.xupdate.entity.PromptEntity;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.proxy.IUpdatePrompter;
import com.xuexiang.xupdate.proxy.IUpdateProxy;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xupdate.utils.UpdateUtils;
import com.xuexiang.xupdate.widget.UpdateDialog;
import com.xuexiang.xutil.display.HProgressDialogUtils;

import java.io.File;

import top.wuhaojie.installerlibrary.AutoInstaller;

public class CustomUpdatePrompter  implements IUpdatePrompter {
    private Context mContext;

    public CustomUpdatePrompter(Context context) {
        mContext = context;
    }

    @Override
    public void showPrompt(@NonNull UpdateEntity updateEntity, @NonNull IUpdateProxy updateProxy, @NonNull PromptEntity promptEntity) {
        showUpdatePrompt(updateEntity, updateProxy,promptEntity);
    }

    /**
     * 显示自定义提示
     *
     * @param updateEntity
     * @param updateProxy
     */
    private void showUpdatePrompt(final @NonNull UpdateEntity updateEntity, final @NonNull IUpdateProxy updateProxy, @NonNull PromptEntity promptEntity) {
        UpdateDialog.newInstance(updateEntity,updateProxy,promptEntity);
        final String updateInfo = UpdateUtils.getDisplayUpdateInfo(mContext, updateEntity);


                        updateProxy.startDownload(updateEntity, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                            @Override
                            public void onStart() {
                                HProgressDialogUtils.showHorizontalProgressDialog(mContext, "检查到新版本，下载完成后，请手动安装\n"+updateInfo, false);
                            }

                            @Override
                            public void onProgress(float progress, long total) {
                                HProgressDialogUtils.setProgress(Math.round(progress * 100));
                            }

                            @Override
                            public boolean onCompleted(File file) {
                                HProgressDialogUtils.cancel();
                                //ToastUtils.toast(updateInfo + file.getPath());

                                /*Intent intent=new Intent(Intent.ACTION_VIEW);

                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");

                                mContext.startActivity(intent);*/
                                AutoInstaller installer = new AutoInstaller.Builder(mContext).build();
                                installer.setOnStateChangedListener(new AutoInstaller.OnStateChangedListener() {
                                    @Override
                                    public void onStart() {
                                        Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
                                        PendingIntent restartIntent =
                                                PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                                        AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

                                        long delayTime = SystemClock.elapsedRealtime()+10000;
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0及以上
                                            mgr.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, delayTime, restartIntent);

                                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4及以上
                                            mgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, delayTime, restartIntent);
                                        }

                                        // 当后台安装线程开始时回调
                                        HProgressDialogUtils.showHorizontalProgressDialog(mContext, "安装正在进行。。。请耐心等待", false);

                                    }
                                    @Override
                                    public void onComplete() {
                                        // 当请求安装完成时回调
                                        HProgressDialogUtils.cancel();
                                    }
                                    @Override
                                    public void onNeed2OpenService() {
                                        // 当需要用户手动打开 `辅助功能服务` 时回调
                                        // 可以在这里提示用户打开辅助功能
                                        Toast.makeText(mContext, "请打开辅助功能服务", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                installer.install(file);
                                return false;
                            }

                            @Override
                            public void onError(Throwable throwable) {
                                HProgressDialogUtils.cancel();
                            }
                        });

    }

}
